declare const message: { [k: string]: string }

const vscode = acquireVsCodeApi();
const root = document.querySelector('#app') as HTMLDivElement;
window.addEventListener('message', onmessage)

const appState = {
    projects: [] as ProjectCache[]
}

vscode.postMessage({ type: 'getProjects' });

function onmessage(e: MessageEvent) {
    const { type, data } = e.data;
    switch (type) {
        case 'setProjects':
            setProjects(data);
    }
}

function saveState(key: string, value: any) {
    if (String(value).trim() === '') {
        return
    }
    const state = vscode.getState() || {}
    state[key] = value
    vscode.setState(state)
}

function onItemClick(e: MouseEvent, index: number, url: string) {
    if (e.button == 0) {
        vscode.postMessage({ type: 'openFolder', data: url });
    } else if (e.button == 2) {
        vscode.postMessage({ type: 'removeFolder', data: url });
        appState.projects.splice(index, 1);
        render()
    }

}

function openFolder() {
    vscode.postMessage({ type: 'openFolder', data: '' });
}

function render() {
    const ar = appState.projects
    const temp: string[] = []
    for (let i = 0; i < ar.length; i++) {
        const url = ar[i].path.replaceAll('\\', '\\\\');
        const defaulIcon = '<svg t="1752116212957" class="icon" viewBox="0 0 1228 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4921" width="64" height="64"><path d="M1228.544 306.304a153.6256 153.6256 0 0 0-153.6256-153.9072h-460.032l21.4272 8.7808L481.024 8.96 472.064 0.256H0.9472v863.36c0 85.248 68.6592 154.368 153.2928 154.368h906.4448c16.9472 0 30.72-13.824 30.72-30.8224 0-17.0496-13.7728-30.848-30.72-30.848H154.2144c-50.688 0-91.904-41.4976-91.904-92.672V31.0784l-30.72 30.8224h428.032l-21.4272-8.7552 155.264 152.192 8.9344 8.7552h472.5248a92.1088 92.1088 0 0 1 92.2368 92.2112V849.92c0 17.024 13.7216 30.8224 30.6688 30.8224 16.9728 0 30.72-13.7984 30.72-30.8224V306.304z m-61.3888 172.032l0.2048-61.696H62.4128v61.696h1104.7424z" fill="#ffffff" p-id="4922"></path></svg>'
        const icon = `<img src="${ar[i].icon}"/>`
        const items = `
        <li>
            <button class="btn com-btn" title="${url}" onmousedown="onItemClick(event,${i},'${url}')">
                ${ar[i].icon?icon:defaulIcon}
                <span>
                ${ar[i].name}
                </span>
            </button>
        </li>
    `
        temp.push(items)
    }

    if (temp.length > 0) {
        const html = `<ul class="projects">${temp.join('')}</ul>`
        root.innerHTML = html
    } else {
        root.innerHTML = `<button class="btn vs-code-btn" onclick="openFolder()">${message.openFolder}</button>`
    }
}

function setProjects(ar: ProjectCache[]) {
    appState.projects = ar;
    render()
}

(window as any).onItemClick = onItemClick;
(window as any).openFolder = openFolder;